from io import BytesIO
from typing import Dict

from fastapi import APIRouter
from minio.error import S3Error
from seaman.core import JsonUtil

from common.method import *
from common.model import InterpolationData
from common.params import ReqSoftParams, SoftParams
from service.DataPreService import read_interpolation_data


router = APIRouter()
from model.soft.descent_depth import run as descent_run

@router.post('/v3/descent/data')
async def descent_depth_data(params: ReqSoftParams):
    # 计算 MD5 哈希值
    md5_hash = params.calc_md5()
    # 获取井号
    wellId: str = params.wellId
    # 获取间距
    space: float = params.space
    # 获取是否有造斜点
    is_slanting_point = params.is_slanting_point
    # 构建对象名称
    data_object_name = wellId + '/' + md5_hash + '-descent_depth.xlsx'
    print(data_object_name)
    # 是否加入液体阻力 @TODO 如果为true就加入 否则加0
    is_Not_add_resistance = params.add_liquid_resistance
    try:
        client.stat_object('well', data_object_name)
        print('已存在对应下入深度分析数据')
        file_data = client.get_object("well", data_object_name)
        df = pd.read_excel(BytesIO(file_data.read()))
        data_list = []
        for index, row in df.iterrows():
            data_list.append(row)
    except S3Error:
        print('不存在下入深度分析数据')
    # 参数预处理
    soft_params: SoftParams = SoftParams(params)
    # 获取插值数据
    _list_: List[InterpolationData] = read_interpolation_data(wellId, space, is_slanting_point)
    inc_depth: float = _list_[-1].depth
    # 获取给定的井斜角的值
    inc_value = params.inclination
    inc_dict: Dict = {}
    for item in _list_:
        inc_dict[item.depth] = item.inclination
        if item.inclination > inc_value:
            inc_depth = item.depth
            break
    # 计算的间距
    calculate_space = params.calculate_space
    last_depth = _list_[-1].depth
    # 设置间隔深度列表
    desired_depths = [last_depth]
    # 从最后一个深度开始，减去间距，直到小于间距为止 这样就只计算部分深度
    while desired_depths[-1] > calculate_space:
        new_value = desired_depths[-1] - calculate_space
        desired_depths.append(new_value)
        # 对列表进行排序并去除重复值
    desired_depths = sorted(set(desired_depths), reverse=True)
    # 是否加入液体阻力 @TODO 如果为true就加入 否则加0
    is_Not_add_resistance = params.add_liquid_resistance
    print("当前的井斜角对应的深度为为", inc_depth)
    # print(inc_dict)
    result = descent_run(soft_params, inc_depth, _list_, is_Not_add_resistance, desired_depths)
    save('well', data_object_name, result)
    return result

